package org.example.user.controller;

import org.example.user.vo.UserExcelVO;
import org.springframework.web.bind.annotation.GetMapping;

import cn.idev.excel.FastExcel;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/excel")
public class ExcelController {

    private static final String UTF_8 = "UTF-8";
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 1. 设置响应头（防止中文乱码）
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        String fileName = URLEncoder.encode("用户数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 2. 生成测试数据（100万行）
        List<UserExcelVO> data = buildData();

        // 3. 使用 FastExcel 导出
        try {
            FastExcel.write(response.getOutputStream(), UserExcelVO.class)
                    .sheet("用户列表")
                    .doWrite(data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<UserExcelVO> buildData() {
        List<UserExcelVO> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            UserExcelVO user = new UserExcelVO();
            user.setUserId(Long.valueOf(i));
            user.setUsername("用户" + i);
            user.setRealName("真实姓名" + i);
            user.setDeptId(Long.valueOf(i));
            user.setDeptName("部门" + i);
            list.add(user);
        }
        return list;
    }
}